/********************************************************************************
 * Project Name		[JavaEE_Web]
 * File Name     	[LastAccessTimeServlet.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package cookie;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 记录用户上一次的访问时间
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
@WebServlet(name = "LastAccessTimeServlet", urlPatterns = "/lastAccessTime")
public class LastAccessTimeServlet extends HttpServlet {

	private static final long serialVersionUID = -3948006685666167753L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		PrintWriter out = response.getWriter();

		// 获得浏览器所有的Cookie
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			out.write("上次访问时间是: ");
			for (Cookie cookie : cookies) {
				if ("lastAccessTime".equals(cookie.getName())) {
					long lastAccess = Long.parseLong(cookie.getValue());
					Date accessDate = new Date(lastAccess);
					out.write(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(accessDate));
				}
			}
		} else {
			out.write("这是第一次访问本站");
		}
		Cookie newCookie = new Cookie("lastAccessTime", String.valueOf(System.currentTimeMillis()));
		newCookie.setMaxAge(24 * 60 * 60);// 有效期为一天
		response.addCookie(newCookie);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}
}
